<script setup>
import {getMessageList, _sendMsg, makeAsRead} from '@/api/im'
import {computed, onActivated, onDeactivated, ref} from "vue";
import {toast} from "@/hook/toast";
import MsgItem from './com/msg-item.vue'
import {delay} from "@/utils";
import IM from '@/ws'
import {useStore} from "vuex";

const page = ref(1)
const loading = ref(false)
const noMore = ref(false)
const list = ref([])
const disabledScroll = computed(() => loading.value || noMore.value)

function onMessage(data) {
  console.log(data, '^_^')
  reset()
}

function reset() {
  page.value = 1
  list.value = []
  noMore.value = false
  initData()
}

onActivated(() => {
  IM.bindEvent('onMessage', onMessage)
  reset()
})
onDeactivated(() => {
  IM.removeEvent('onMessage')
})

async function initData() {
  if (loading.value) return
  loading.value = true
  const resp = await getMessageList({page: page.value})
  const {code, data, msg} = resp
  await delay(300)
  loading.value = false
  if (code !== 1) {
    return toast({title: msg, type: 'error'})
  }
  if (!data.data) data.data = []
  const {data: msgList, total, current_page, per_page} = data

  function patchZero(value) {
    return ('0' + value).slice(-2)
  }

  function format(timestamp) {
    const date = new Date(timestamp)
    const [year, month, day, hour, minute, seconds] = [date.getFullYear(), date.getMonth() + 1, date.getDate(), date.getHours(), date.getMinutes(), date.getSeconds()]
    return `${year}-${patchZero(month)}-${patchZero(day)} ${patchZero(hour)}:${patchZero(minute)}:${patchZero(seconds)}`
  }

  list.value.push(...msgList.map(item => {
    const {content, title, is_see, id, createtime} = item
    return {
      content,
      title,
      isRead: is_see > 0,
      id,
      time: format(createtime * 1000),
    }
  }))
  const hasMore = current_page * per_page < total
  noMore.value = !hasMore
  if (hasMore) page.value += 1

}

async function readHandle(record) {
  const {id} = record
  const resp = await makeAsRead({id})
  // console.log(resp, 'resp')
  const {code} = resp
  const title = code < 1 ? '操作失败' : '操作成功'
  toast({title, type: code < 1 ? 'error' : 'success'})
  if (code < 1) return
  IM.updateUnReadCount()
  const target = list.value.find(item => item.id === id)
  if (!target) return
  target.isRead = true
}

async function sendMsg() {
  const resp = await _sendMsg({
    id: '385',
    msg: 'Hello Word!'
  })
  console.log(resp)
}

const store = useStore()
const showBtn = computed(() => store.getters.isDev && store.getters.isWWM)
</script>

<template>
  <div class="full relative msg-wrap" v-loading="loading">
    <div class="message-list-container card_wrap scroll_wrap"
         :infinite-scroll-disabled="disabledScroll"
         v-infinite-scroll="initData"
         :infinite-scroll-immediate="false"
    >
      <el-button v-if="showBtn" type="primary" @click="sendMsg">发送消息</el-button>
      <msg-item v-for="(item,index) in list" :key="index" :record="item" @read="readHandle"/>
      <div class="no-more" v-if="noMore">
        <span>--我是有底线的--</span>
      </div>
    </div>
  </div>
</template>

<style scoped lang="scss">
.msg-wrap {
  //padding-bottom: 8px;
  box-sizing: border-box;
}

.message-list-container {
  overflow-y: scroll;
  position: relative;

  :deep(.el-loading-mask) {
    border: 1px solid red;
    height: 100%;
  }

  .no-more {
    text-align: center;
    padding: 16px;
    font-size: 14px;
    color: #909399;
  }
}

</style>
